//
//  ViewController2.swift
//  SWIFTLEARN
//
//  Created by chichaojituan521 on 2017/5/12.
//  Copyright © 2017年 linch. All rights reserved.
//

import UIKit

class ViewController2: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource,UIScrollViewDelegate {

    var view1:UIView?
    var view2:UIView?
    var view3:UIView?
    var segmented:UISegmentedControl?
    var progressView:UIProgressView?
    var slider:UISlider?
    var pickerView:UIPickerView!
    var stepper:UIStepper!
    var label:UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.lightGray
        view2 = UIView(frame: self.view.frame)
        self.view.addSubview(view2!)
        view2?.backgroundColor = UIColor.orange
        
        view3 = UIView(frame: self.view.frame)
        self.view.addSubview(view3!)
        view3?.backgroundColor = UIColor.yellow

        
        view1 = UIView(frame: self.view.frame)
        self.view.addSubview(view1!)
        view1?.backgroundColor = UIColor.lightGray
        
        
        self.segmentControlMethod()
        
        //MARK:*****************第一个view*******************************************
        let btnName:[String] = ["新增分页","删除分页","修改分页","UIImageView","UIProgressView","UISlider","UIPickerView","UIstepper","UIScrollView","UIGestureRecognizer","UIButtonUISwith","退出"]
        
        let btnInterval: Int = 10
        
        let btnWidth = (self.view.frame.size.width - CGFloat(btnInterval) * 5)/4.0
        
        
        for btnitem in 1...12 {
            
            let item = btnitem - 1
            
            let button = UIButton(type: .custom)
            button.tag = btnitem
            
            view1?.addSubview(button)
            
            button.setTitle(btnName[item], for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 13)
            button.titleLabel?.lineBreakMode = .byWordWrapping
            button.backgroundColor = UIColor.orange
            
            let btncgx = btnInterval + (Int(item) % 4) * (Int(btnWidth) + btnInterval)
            let btncgy = 74 + (Int(item) / 4) * (btnInterval + 50)
            button.frame = CGRect(x:btncgx , y:btncgy , width: Int(btnWidth), height: 50)
            
            button.addTarget(self, action: #selector(buttonClickMethod(_:)),for: .touchUpInside)
            
        }
        //MARK:*****************第二个view*******************************************
    }
    func buttonClickMethod(_ button:UIButton) {
        
        switch button.tag {
        case 1:
            self.addSegmentedMethod()
        case 2:
            self.deleteSegmentedMethod()
        case 3:
            self.changeSegmentedMethod()
        case 4:
            self.imageViewBuildMethod()
        case 5:
            self.UIProgressViewMethod()
        case 6:
            self.UISliderMethod()
        case 7:
            self.UIPickerViewMethod()
        case 8:
            self.UIstepperMethod()
        case 9:
            self.UIScrollViewMethod()
        case 10:
            self.UIGestureRecognizerMethod()
        case 11:
            self.UIDatePickerMethod()
        case 12:
            self.PopVCMethod()
            
        default:
            print("case===")
        }
    }
    
    func PopVCMethod() {
        self.dismiss(animated: true) {
            
        }
    }
    func segmentControlMethod() {
        
        let items = ["热点","精选","最新"]
        
        segmented = UISegmentedControl(items: items)
        
        segmented!.selectedSegmentIndex = 0
        segmented!.addTarget(self, action: #selector(segmentMethod(_:)), for: .valueChanged)
        segmented!.frame = CGRect(x: (self.view.frame.size.width - 200)/2.0, y: 20, width: 200, height: 30)
        //添加到navigation 上
        self.navigationItem.titleView = segmented
        
    }
    //MARK:--分页按钮触发
    func segmentMethod (_ segment:UISegmentedControl) {
        switch segment.selectedSegmentIndex {
        case 0:
            self.view.bringSubview(toFront: view1!)
        case 1:
            self.view.bringSubview(toFront: view2!)
        case 2:
            self.view.bringSubview(toFront: view3!)
        case 3:
            print("0000099")
        default:
            print("没有了")
            
        }
    }
    //MARK:--新增分页
    func addSegmentedMethod () {
        segmented?.insertSegment(withTitle: "火爆", at: 3, animated: true)
        segmented?.insertSegment(with: UIImage(named:"btnbtn")?.withRenderingMode(.alwaysOriginal), at: 4, animated: true)
    }
    //MARK:--删除分页
    func deleteSegmentedMethod () {
        segmented?.removeSegment(at: 3, animated: true)
    }
    //MARK:--修改分页
    func changeSegmentedMethod () {
//        segmented?.setImage(UIImage(named:"天天购.jpg"), forSegmentAt: 3)
        segmented?.setImage(UIImage(named:"天天购.jpg")?.withRenderingMode(.alwaysOriginal), forSegmentAt: 3)
        segmented?.setTitle("swfit", forSegmentAt:1)
        
        
    }
    //MARK:--imageView
    func imageViewBuildMethod () {
        
        let imageView1 = UIImageView()
        imageView1.frame = CGRect(x:10, y:250, width:100, height:100)
        view1?.addSubview(imageView1)
        
        let imageView2 = UIImageView()
        imageView2.frame = CGRect(x:120, y:250, width:100, height:100)
        view1?.addSubview(imageView2)
        
        let imageView3 = UIImageView()
        imageView3.frame = CGRect(x:230, y:250, width:100, height:100)
        view1?.addSubview(imageView3)
//        从文件目录中获取图片 
        let pathIcon = Bundle.main.path(forResource: "btnbtn", ofType: "png")
        let newImage = UIImage(contentsOfFile: pathIcon!)
        imageView1.image = newImage
//        从网络地址获取图片 
        let urlIcon = URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1495011427097&di=6c45af6fa4ae614b2506d6d3988cace8&imgtype=0&src=http%3A%2F%2Fwww.jrait.com%2Fbook_cover%2Fbd1225834.jpg")
        let dataImg = try!Data(contentsOf: urlIcon!)
        let imgUrl = UIImage(data: dataImg)
        imageView2.image = imgUrl
        
        //保持图片比例
        imageView2.contentMode = .scaleAspectFit
        
        print(pathIcon!)
//        
        var array = [UIImage]();
        
        for item in 0...39 {
            let name = "eat_" + String(item) + ".jpg";
            let img = UIImage(named: name);
            array.append(img!);
        }
        
        
        imageView3.animationImages = array;
        imageView3.animationDuration = 3;
        imageView3.startAnimating();
        
        
        
    }
    //MARK:--UIProgressView
    func UIProgressViewMethod()   {
        
        progressView = UIProgressView(progressViewStyle: .default);
        progressView?.center = self.view.center;
        progressView?.progress = 0.4;
//        改变进度条颜色 
        
        progressView?.trackTintColor = UIColor.blue;   //yes
        progressView?.progressTintColor = UIColor.red;  //no
        self.view.addSubview(progressView!);
        self.perform(#selector(setProgressValue), with: nil, afterDelay: 3);
        
    }
    func setProgressValue()  {
        progressView?.setProgress(0.9, animated: true);
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        }
    //MARK: --UISlider
    func UISliderMethod() {
        slider=UISlider(frame:CGRect(x: 50, y: 400, width: 250, height: 50));
//        slider?.center=self.view.center
        slider?.minimumValue=0  //最小值
        
        slider?.maximumValue=1  //最大值
        slider?.value=0.5  //当前默认值
        
        slider?.isContinuous=false  //滑块滑动停止后才触发ValueChanged事件
        self.view.addSubview(slider!)
        
        
        
//        滑块左右两边槽的颜色
        
        slider?.minimumTrackTintColor=UIColor.red  //左边槽的颜色
        slider?.maximumTrackTintColor=UIColor.green //右边槽的颜色
//        滑块后面槽线两侧添加图标
        slider?.minimumValueImage=UIImage(named:"11111")  //左边图标
        slider?.maximumValueImage=UIImage(named:"2222")  //右边图标
        
//        设置滑块的值，同时有动画
        slider?.setValue(0.8,animated:true)
        progressView?.setProgress((slider?.value)!, animated: true);
        
        slider?.addTarget(self, action: #selector(sliderDidchange(_:)), for: .valueChanged);
        
        slider?.setThumbImage(UIImage(named:"333"),for:.normal)
        
    }
    func sliderDidchange(_ slider:UISlider){
        progressView?.setProgress(slider.value, animated: true);
    }
    func UIPickerViewMethod(){
        pickerView = UIPickerView()
        pickerView.frame = CGRect(x: 75, y: 300, width: 200, height: 100)
        pickerView.backgroundColor = UIColor.green
        pickerView.dataSource = self;
        pickerView.delegate = self;
        
        pickerView.selectRow(2, inComponent: 1, animated: true)
        self.view.addSubview(pickerView);
        
        let button = UIButton(frame: CGRect(x: 100, y: 450, width: 100, height: 50));
        self.view.addSubview(button)
        button.addTarget(self, action: #selector(buttonClickMethodPickerView(_:)), for: .touchUpInside)
        
        button.backgroundColor = UIColor.brown
        
    }
    func buttonClickMethodPickerView(_ sender:UIButton) {
        let message = String(pickerView.selectedRow(inComponent: 0)) + "-"
            + String(pickerView.selectedRow(inComponent: 1)) + "-"
            + String(pickerView.selectedRow(inComponent: 2))
        
        let alertController = UIAlertController(title: "被选中的索引为",
                                                message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
        
        let cancleAction = UIAlertAction(title: "cancle", style: .default, handler: nil)
        alertController.addAction(okAction)
        alertController.addAction(cancleAction)
        self.present(alertController, animated: true, completion: nil)
    
    }
    //MARK: --pickerview  delegate
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 3;
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 40
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return String(row)+"-"+String(component)
    }
    
    
    //设置列宽
    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        if(0 == component){
            //第一列变宽
            return 80
        }else{
            //第二、三列变窄
            return 50
        }
    }
    
    //设置行高
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 50
    }
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int,reusing view: UIView?) -> UIView {
        let image = UIImage(named:"eat_"+String(row)+".jpg")
        let imageView = UIImageView()
        imageView.image = image
        return imageView
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        //将在滑动停止后触发，并打印出选中列和行索引
        print(component)
        print(row)
    }
    //MARK: --步进器
    func UIstepperMethod ()
    {
        stepper=UIStepper()
        stepper.center=self.view.center
        //设置stepper的范围与初始值
        stepper.maximumValue=100
        stepper.minimumValue=1
        stepper.value=5.5
        //设置每次增减的值
        stepper.stepValue=0.5
        //设置stepper可以按住不放来连续更改值
        stepper.isContinuous=true
        //设置stepper是否循环（到最大值时再增加数值从最小值开始）
        stepper.wraps=true
        stepper.addTarget(self, action: #selector(stepperValueIschanged), for: .valueChanged)
        self.view.addSubview(stepper)
        label=UILabel(frame:CGRect(x:100,y:190,width: 300,height:30))
        print(stepper.value)
        label.text = "当前值为：\(stepper.value)"
        self.view.addSubview(label)
    }
    func stepperValueIschanged ()
    {
        label.text="当前值为：\(stepper.value)"
    }
    
    //MARK: - UIScrollView
    func UIScrollViewMethod (){
        
        let scrollView = UIScrollView(frame: CGRect(x: 40, y: 150, width: 300, height: 300));
        scrollView.backgroundColor = UIColor.green
        scrollView.contentSize = CGSize(width: 300, height: 800)
        self.view.addSubview(scrollView)
        scrollView.delegate = self
        
        let imageVeiw = UIImageView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
        scrollView.addSubview(imageVeiw)
        imageVeiw.image = UIImage(named:"btnbtn");
        
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
         print("x:\(scrollView.contentOffset.x) y:\(scrollView.contentOffset.y)")
    }
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        print("开始pan")
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        print("结束panANI")
    }
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        print("结束pan")
    }
    
    //MARK: -- UIGestureRecognizer
    func UIGestureRecognizerMethod ()  {
        
        //滑动
        let swipe = UISwipeGestureRecognizer(target: self, action: #selector(swipe(_ :)))
        swipe.direction = .up
        
        self.view.addGestureRecognizer(swipe)
        
        //边缘滑动
        let swipeEdge = UIScreenEdgePanGestureRecognizer(target:self, action:#selector(swipeEdge(_:)))
        swipeEdge.edges = UIRectEdge.left //从左边缘开始滑动
        self.view.addGestureRecognizer(swipeEdge)
//        UITapGestureRecognizer：轻点手势（点击）
        let tapGest = UITapGestureRecognizer(target: self, action: #selector(tapMethod(_:)))
        tapGest.numberOfTapsRequired = 1;   //手指数
        tapGest.numberOfTouchesRequired = 2;   //次数
        self.view.addGestureRecognizer(tapGest)
        
        //UIPinchGestureRecognizer：捏合手势
        let pinch = UIPinchGestureRecognizer(target:self,action:#selector(pinchDid(_:)))
        self.view.addGestureRecognizer(pinch)
        
        
        //旋转手势
        let rotation = UIRotationGestureRecognizer(target:self,
        action:#selector(rotationDid(_:)))
        self.view.addGestureRecognizer(rotation)
        
        
        //UIPanGestureRecognizer：拖动手势 
        let pan = UIPanGestureRecognizer(target:self,action:#selector(panDid(_:)))
        pan.maximumNumberOfTouches = 1
        self.view.addGestureRecognizer(pan)
//        长按
        //长按监听
        let longPress = UILongPressGestureRecognizer(target:self,
                                                     action:#selector(longPressDid(_:)))
        self.view.addGestureRecognizer(longPress)
        
    }
    func swipe(_ swipe:UISwipeGestureRecognizer){
        print("向上swipe")
        let point=swipe.location(in: self.view)
        //这个点是滑动的起点
        print(point.x)
        print(point.y)
    }
    func swipeEdge(_ gestureEdge:UIScreenEdgePanGestureRecognizer){
        print("left edgeswipe ok")
        let point=gestureEdge.location(in: self.view)
        //这个点是滑动的起点
        print(point.x)
        print(point.y)
    }
    func tapMethod(_ tap:UITapGestureRecognizer){
         print("单击了")
    }
    func pinchDid(_ recognizer:UIPinchGestureRecognizer) {
        //在监听方法中可以实时获得捏合的比例
        print(recognizer.scale);
    }
    func rotationDid(_ recognizer:UIRotationGestureRecognizer){
        //旋转的弧度转换为角度
        print(recognizer.rotation*(180/CGFloat(M_PI)))
    }
    func panDid(_ recognizer:UISwipeGestureRecognizer){
        let point=recognizer.location(in: self.view)
        //设置矩形的位置
        print("---x==\(point.x)----y==\(point.y)")
    }
    func longPressDid(_ sender: UILongPressGestureRecognizer){
        if sender.state == .began {
            print("长按响应开始")
        } else {
            print("长按响应结束")
        }
    }

    //MARK : - 时间选择器
    func UIDatePickerMethod() {
        let datePicker = UIDatePicker(frame: CGRect(x:20, y:200, width:320, height:216))
        //将日期选择器区域设置为中文，则选择器日期显示为中文
        datePicker.locale = Locale(identifier: "zh_CN")
        //注意：action里面的方法名后面需要加个冒号“：”
        datePicker.addTarget(self, action: #selector(dateChanged(_:)),
                             for: .valueChanged)
        self.view.addSubview(datePicker)
        datePicker.datePickerMode = .date        /////.time
        datePicker.setValue(UIColor.white, forKey: "textColor")      //修改文字颜色
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let minDate = dateFormatter.date(from: "2006-5-20")
        datePicker.minimumDate = minDate
        datePicker.maximumDate = Date()
    }
    func dateChanged(_ datePicker : UIDatePicker){
        //更新提醒时间文本框
        let formatter = DateFormatter()
        //日期样式
        formatter.dateFormat = "yyyy年MM月dd日 HH:mm:ss"
        print(formatter.string(from: datePicker.date))
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

   }
